#include <math.h>
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int v)
        : val(v), left(nullptr), right(nullptr)
    {
    }
};
class Solution
{
    int Sum(TreeNode* root)
    {
        if (root == nullptr)
        {
            return 0;
        }
        else
        {
            return Sum(root->left) + Sum(root->right) + root->val;
        }
    }
    void CreateTilt(TreeNode *root, TreeNode*& TileRoot)
    {
        if (root == nullptr)
        {
            return;
        }
        else
        {
            int leftSum = Sum(root->left);
            int rightSum = Sum(root->right);
            TileRoot = new TreeNode(abs(leftSum - rightSum));
            CreateTilt(root->left, TileRoot->left);
            CreateTilt(root->right, TileRoot->right);
        }
    }

public:
    int findTilt(TreeNode *root)
    {
        TreeNode *TileRoot;
        CreateTilt(root, TileRoot);
        return Sum(TileRoot);
    }
};